﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using FreedomX2.Core.Log;

namespace FreedomX2.Core.Transport.SocketProvider
{
    public class SocketServer
    {

        #region 内部存储空间定义
        private int _port = ProtocolVar.DefaultPort;
        private System.Net.Sockets.TcpClient _tcpC;
        private System.Net.Sockets.TcpListener _tcpL;
        private bool _tcpState = false;
        private Thread _eTh;
        private Thread _eSocketTh;
        private string _eIp = ProtocolVar.DefaultIP;
        private System.Net.Sockets.Socket _eSocket;
        #endregion

        #region 内部事件定义


        #endregion

        #region 外部方法
        /// <summary>
        /// 构造类
        /// </summary>
        public SocketServer(string serip, int serpoint)
        {
            //构造
            _eIp = serip;
            _port = serpoint;
        }

        /// <summary>
        /// 开始侦听
        /// </summary>
        public void ServerStart()
        {
            _eTh = new Thread(new ThreadStart(thListen));
            _eTh.Start();
        }

        /// <summary>
        /// 停止侦听
        /// </summary>
        public void ServerStop()
        {
            try
            {
                _tcpL.Stop();
                _tcpState = false;
                _eSocketTh.Abort();
            }
            catch (Exception ex) { ex.e(); }
            try
            {
                _eTh.Abort();
            }
            catch (Exception ex) { ex.e(); }
            ("服务在" + _eIp + ":" + _port.ToString() + "已停止").l();
        }

        ~SocketServer()
        {
            //析构
            _eTh.Abort();
        }

        /// <summary>
        /// Listener线程
        /// </summary>
        private void thListen()
        {

            try
            {
                Int32 portS = _port;
                IPAddress localaddr = IPAddress.Parse(_eIp);
                _tcpL = new TcpListener(localaddr, portS);
                _tcpL.Start();
                ("服务在" + _eIp + ":" + _port.ToString() + "已启动").l();

                while (true)
                {
                    System.Threading.Thread.Sleep(200);
                    System.Net.Sockets.Socket s = _tcpL.AcceptSocket();
                    _eSocket = s;
                    _eSocketTh = new Thread(new ThreadStart(thSocket));
                    _eSocketTh.Start();

                }
            }
            catch (System.Exception ex)
            {
                ex.e();
            }
            finally
            {
                _tcpL.Stop();
            }
        }

        private void thSocket()
        {
            System.Net.Sockets.Socket client = _eSocket;
            if (Envior.Ment.ISLOGSTART) Envior.Ment.MARKSTRING = "SOCKETIP" + client.RemoteEndPoint.ToString();
            bool keepalive = true;

            while (keepalive)
            {
                Byte[] buffer = new Byte[ProtocolVar.DefaultPackageSize];
                int bufLen = 0;
                try
                {
                    bufLen = client.Available;

                    client.Receive(buffer, 0, bufLen, SocketFlags.None);
                    if (bufLen == 0) continue;
                }
                catch (System.Exception ex)
                {
                    ex.e();
                    return;
                }

                SocketThread.ReceiveBytes(client, buffer);
            }
        }
        #endregion

        #region 属性
        /// <summary>
        /// 当前Listener线程
        /// </summary>
        public System.Threading.Thread CurrThread
        {
            get
            {
                return _eTh;
            }
            set
            {
                _eTh = value;
            }
        }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port
        {
            get
            {
                return _port;
            }
            set
            {
                _port = value;
            }
        }

        /// <summary>
        /// 当前Client
        /// </summary>
        public System.Net.Sockets.TcpClient TCPClient
        {
            get
            {
                return _tcpC;
            }
            set
            {
                _tcpC = value;
            }
        }

        /// <summary>
        /// 当前Listener
        /// </summary>
        public System.Net.Sockets.TcpListener TCPListener
        {
            get
            {
                return _tcpL;
            }
            set
            {
                _tcpL = value;
            }
        }

        /// <summary>
        /// 当前连接状态
        /// </summary>
        public bool ConState
        {
            get
            {
                return _tcpState;
            }
            set
            {
                _tcpState = value;
            }
        }

        /// <summary>
        /// IP地址
        /// </summary>
        public string IP
        {
            get
            {
                return _eIp;
            }
            set
            {
                _eIp = value;
            }
        }

        #endregion
    }
}
